/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package business;

import domain.CurrentUser;
import domain.LoginError;
import java.net.PasswordAuthentication;
import persistence.LoginPersistence;

/**
 *
 * @author admin
 */
public class LoginBusiness {
/**
     * Authenticates the user
     * @param holder a Data structure that holds the username and password
     * @return A LoginError object containing the details of the error occurred
     */
    public LoginError authenticate(PasswordAuthentication holder) {
        LoginError error = new LoginError();
        LoginPersistence lp = new LoginPersistence();

        if (validateInput(holder)) {
            String password = lp.getPassword(holder.getUserName());
            if (password == null) {
                error.setIncorrectDetails(true);
                error.setMessage("The username or password entered is wrong");
            } else {
                if (!password.equals(new String(holder.getPassword()))) {
                    error.setIncorrectDetails(true);
                    error.setMessage("The username or password entered is wrong");
                }
            }
        } else {
            error.setValidationError(true);
            error.setMessage("Please fill all the fields");
        }
        return error;
    }
/**
     * Validates the user input
     * @param holder a Data structure that holds the username and password
     * @return true if the inputs are valid
     */
    private boolean validateInput(PasswordAuthentication holder) {
        int errorCount = 0;
        if (holder.getUserName().length() == 0) {
            errorCount++;
        }
        if (holder.getPassword().length == 0) {
            errorCount++;
        }
        if (errorCount == 0) {
            return true;
        } else {
            return false;
        }

    }
/**
     * Keeps track of the logged in user
     * @param username The username of the logged in user
     */
    public void addCurrentUser(String username) {
        LoginPersistence loginPersistence = new LoginPersistence();
        int userID = loginPersistence.getUserId(username);
        if (userID > 0) {
            CurrentUser.setUser_id(userID);
            CurrentUser.setUsername(username);
        }
    }
}
